package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"lx/cache"
	"lx/models"
	"net/http"
	"strconv"
	"time"
)

func OrderAdd(c *gin.Context) {
	orderno := c.PostForm("orderno")
	formaddress := c.PostForm("address")
	toaddress := c.PostForm("toaddress")
	cid, _ := strconv.Atoi(c.PostForm("cid"))

	order := models.Order{
		OrderNo:     orderno,
		FormAddress: formaddress,
		ToAddress:   toaddress,
		Cid:         cid,
	}

	models.DB.Create(&order)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": order,
	})
	return
}

func OrderCarList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var orderlist []models.OrderList
	list := "list" + strconv.Itoa(page)
	key, _ := cache.Rdb.Get(cache.Ctx, list).Result()
	if key == "" {
		models.DB.Table("orders").
			Joins("left join cars on cars.id = orders.cid").
			Select(
				"orders.order_no as OrderNo",
				"orders.form_address as FormAddress",
				"orders.to_address as ToAddress",
				"cars.code as Code",
				"cars.name as Name",
				"cars.num as Num").Offset(offset).
			Limit(size).Debug().Find(&orderlist)
		jsonData, _ := json.Marshal(orderlist)
		cache.Rdb.Set(cache.Ctx, list, jsonData, time.Hour*3)
	} else {
		json.Unmarshal([]byte(key), &orderlist)
	}

	var count int64
	models.DB.Model(&models.Order{}).Count(&count)

	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  orderlist,
		"count": count,
	})
	return
}

func OrderDetail(c *gin.Context) {
	id := c.Query("id")
	var order models.Order
	list := "list" + id
	key, _ := cache.Rdb.Get(cache.Ctx, list).Result()
	if key == "" {
		models.DB.First(&order, id)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, list, jsonData, time.Hour*3)
	} else {
		json.Unmarshal([]byte(key), &order)
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": order,
	})
	return
}
